package com.fjnu.springmvc.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
public class LoginHandler implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        log.info("uri: {}", uri) ;

        //判断当前请求地址是否登录地址or注册地址
        if(uri.contains("Login") || uri.contains("login")
                || uri.endsWith("/") || uri.contains("/static/") || uri.contains("/register")
                || uri.contains("/regi")) {
            //登录请求，直接放行
            return true;
        }else {
            //判断用户是否登录
            if(request.getSession().getAttribute("user") != null) {
                //说明已经登录，放行
                log.info("LoginHandler:user:" + request.getSession().getAttribute("user"));
                return true;
            } else {
                log.info("blocked: {}",  uri) ;
                //没有登录，跳转到登录界面
                response.sendRedirect(request.getContextPath() + "/");
            }
        }

        //默认拦截
        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
